package com.cq.hd.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.admin.annotation.RequiresPermissionsDesc;
import com.cq.hd.admin.dto.BusinessMemberFeeBillPageDto;
import com.cq.hd.admin.po.TbAdminUserPo;
import com.cq.hd.admin.service.TbAdminUserService;
import com.cq.hd.admin.vo.BusinessMemberFeeBillPageVo;
import com.cq.hd.common.enums.biz.PayStateEnum;
import com.cq.hd.common.enums.biz.PayTypeEnum;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Result;
import com.cq.hd.common.response.ResultGenerator;
import com.cq.hd.common.response.Throw;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.TbMemberFeeBillApi;
import com.cq.hd.member.api.TbMemberFeeConfigApi;
import com.cq.hd.member.api.dto.*;
import com.cq.hd.member.api.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 商家表 前端控制器
 * </p>
 *
 * @author mYunYu
 * @since 2023-11-21
 */
@Api(tags = "商家相关接口")
@Slf4j
@RestController
@RequestMapping("/business")
public class TbBusinessController extends BaseController {

    @Autowired
    private TbBusinessApi tbBusinessApi;

    @Autowired
    private TbMemberFeeConfigApi memberFeeConfigApi;

    @Autowired
    private TbMemberFeeBillApi memberFeeBillApi;

    @Autowired
    private TbAdminUserService adminUserService;

    @ApiOperation(value = "商家列表")
    @ApiImplicitParam(name = "businessPageDto", value = "实体", paramType = "query", dataType = "BusinessPageDto")
    @ApiResponse(response = BusinessPageVo.class, code = 200, message = "接口返回对象参数")
    @RequiresPermissions("business:business:list")
    @RequiresPermissionsDesc(menu = {"商家管理", "商家列表"}, button = "查询")
    @GetMapping("/page")
    public Result<Page<BusinessPageVo>> pageBusiness(BusinessPageDto businessPageDto) {
        return tbBusinessApi.pageBusiness(businessPageDto);
    }

    @ApiOperation(value = "关联商户列表")
    @ApiImplicitParam(name = "relationMerchantPageDto", value = "实体", paramType = "query", dataType = "RelationMerchantPageDto")
    @ApiResponse(response = RelationMerchantPageVo.class, code = 200, message = "接口返回对象参数")
//    @RequiresPermissions("business:business:list")
    @RequiresPermissionsDesc(menu = {"商家管理", "关联商户列表"}, button = "查询")
    @GetMapping("/pageRelationMerchant")
    public Result<Page<RelationMerchantPageVo>> pageRelationMerchant(RelationMerchantPageDto relationMerchantPageDto) {
        return tbBusinessApi.pageRelationMerchant(relationMerchantPageDto);
    }

    @ApiOperation(value = "商家详情")
    @ApiImplicitParam(name = "id", value = "商家id", required = true, paramType = "query", dataType = "Long")
    @ApiResponse(response = AdminBusinessPageVo.class, code = 200, message = "接口返回对象参数")
    @RequiresPermissions("business:business:details")
    @RequiresPermissionsDesc(menu = {"商家管理", "商家列表"}, button = "详情")
    @GetMapping("/details")
    public Result<AdminBusinessPageVo> details(Long id) {
        return tbBusinessApi.details(id);
    }

    @ApiOperation(value = "商家会员续费记录列表")
    @ApiResponse(response = BusinessMemberFeeBillPageVo.class, code = 200, message = "接口返回对象参数")
    @RequiresPermissions("business:business:memberFeeBillList")
    @RequiresPermissionsDesc(menu = {"商家管理", "商家列表"}, button = "会员续费记录列表")
    @GetMapping("/memberFeeBillPage")
    public Result<Page<BusinessMemberFeeBillPageVo>> pageBusinessMemberFeeBill(BusinessMemberFeeBillPageDto businessMemberFeeBillPageDto) {
        Long businessId = businessMemberFeeBillPageDto.getBusinessId();
        if (businessId == null || businessId <= 0) {
            Throw.isBusinessException("请选择商家");
        }
        List<BusinessMemberFeeBillPageVo> businessMemberFeeBillPageVos = new ArrayList<>();

        AdminMemberFeeBillPageDto adminMemberFeeBillPageDto = new AdminMemberFeeBillPageDto();
        adminMemberFeeBillPageDto.setPageNum(businessMemberFeeBillPageDto.getPageNum());
        adminMemberFeeBillPageDto.setPageSize(businessMemberFeeBillPageDto.getPageSize());
        adminMemberFeeBillPageDto.setBusinessId(businessId);
        adminMemberFeeBillPageDto.setPayState(PayStateEnum.SUCCESS.getValue());
        Page<AdminMemberFeeBillPageVo> adminMemberFeeBillPageVoPage = memberFeeBillApi.pageAdminMemberFeeBill(adminMemberFeeBillPageDto).unpack();
        List<AdminMemberFeeBillPageVo> list = adminMemberFeeBillPageVoPage.getList();
        if (!CollectionUtils.isEmpty(list)) {
            Map<Integer, TbAdminUserPo> adminUserPoMap = new HashMap<>();
            List<String> adminUserIds = list.stream()
                    .filter(adminMemberFeeBillPageVo -> PayTypeEnum.GIVE.getValue().equals(adminMemberFeeBillPageVo.getPayType()))
                    .map(AdminMemberFeeBillPageVo::getReturnNo)
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(adminUserIds)) {
                List<TbAdminUserPo> adminUserPos = adminUserService.list(new QueryWrapper<TbAdminUserPo>().in("id", adminUserIds));
                if (!CollectionUtils.isEmpty(adminUserPos)) {
                    adminUserPoMap = adminUserPos.stream().collect(Collectors.toMap(TbAdminUserPo::getId, Function.identity(), (k1, k2) -> k2));
                }
            }

            for (AdminMemberFeeBillPageVo adminMemberFeeBillPageVo : list) {
                Integer payType = adminMemberFeeBillPageVo.getPayType();
                String memberName = adminMemberFeeBillPageVo.getMemberName();
                String memberFeeStr;
                if (PayTypeEnum.GIVE.getValue().equals(payType)) {
                    TbAdminUserPo adminUserPo = adminUserPoMap.get(Integer.parseInt(adminMemberFeeBillPageVo.getReturnNo()));
                    if (adminUserPo != null) {
                        memberFeeStr = "后台" + adminUserPo.getUserName() + "赠送" + memberName;
                    } else {
                        memberFeeStr = "后台赠送" + memberName;
                    }
                } else {
                    memberFeeStr = "购买" + memberName;
                }

                BusinessMemberFeeBillPageVo businessMemberFeeBillPageVo = new BusinessMemberFeeBillPageVo();
                businessMemberFeeBillPageVo.setMemberFee(adminMemberFeeBillPageVo.getMemberFee());
                businessMemberFeeBillPageVo.setPayTime(adminMemberFeeBillPageVo.getPayTime());
                businessMemberFeeBillPageVo.setMemberName(memberFeeStr);
                businessMemberFeeBillPageVos.add(businessMemberFeeBillPageVo);
            }
        }

        return ResultGenerator.success(Page.newPageWithAllFields(businessMemberFeeBillPageVos, adminMemberFeeBillPageVoPage.getPageNum(), adminMemberFeeBillPageVoPage.getPageSize(), adminMemberFeeBillPageVoPage.getTotal(), adminMemberFeeBillPageVoPage.getPages()));
    }

    @ApiOperation(value = "赠送会员")
    @ApiResponse(response = Boolean.class, code = 200, message = "接口返回对象参数")
    @RequiresPermissions("business:business:giveMemberFee")
    @RequiresPermissionsDesc(menu = {"商家管理", "商家列表"}, button = "赠送会员")
    @PostMapping("/giveMemberFee")
    public Result<Boolean> giveMemberFee(@RequestBody MemberFeeGiveDto memberFeeGiveDto) {
        memberFeeGiveDto.setAdminUserId(getAdminUserId());
        return memberFeeConfigApi.giveMemberFee(memberFeeGiveDto);
    }

    @ApiOperation(value = "修改权益")
    @ApiResponse(response = Boolean.class, code = 200, message = "接口返回对象参数")
//    @RequiresPermissions("business:business:giveMemberFee")
    @RequiresPermissionsDesc(menu = {"商家管理", "商家列表"}, button = "修改权益")
    @PostMapping("/changeRights")
    public Result<Boolean> changeRights(@RequestBody MemberFeeChangeDto memberFeeChangeDto) {
        memberFeeChangeDto.setAdminUserId(getAdminUserId());
        return memberFeeConfigApi.changeRights(memberFeeChangeDto);
    }
}
